import { ref } from "vue"
import Main from "../main";

export default (main: Main) => {
    const enabled = ref(false)
    const es: any = []
    //
    const toggle = () => {
        enabled.value = !enabled.value;
        close();
        if (enabled.value) {
            open();
        }
    }
    //
    const open = () => {
        const box = main.graph.boxEl;
        const v = document.createElement('div')
        const h = document.createElement('div')
        const c = document.createElement('div')
        //
        v.setAttribute('style', "position:absolute;width:1px;top:0;bottom:0;left:-100px;z-index:1;border-left:1px dashed red");
        h.setAttribute('style', "position:absolute;height:1px;left:0;right:0;top:-100px;z-index:1;border-top:1px dashed red");
        c.setAttribute('style', "position:absolute;display:inline-block;font-size:12px;z-index:1;padding:8px;border-radius:4px;line-height:20px;background:#f6ffed;")
        //
        box?.appendChild(v)
        box?.appendChild(h)
        box?.appendChild(c)
        //
        es.push(v, h, c);
        box?.addEventListener('mousemove', eventFun)
    }

    const close = () => {
        const box = main.graph.boxEl;
        box?.removeEventListener('mousemove', eventFun)
        for (const e of es) {
            e.remove();
        }
        es.length = 0;
    }

    const eventFun = (e: MouseEvent) => {
        const graph = main.graph;
        if (!graph) return;
        const t = e.target;
        if (es.includes(t)) { return; }
        const [v, h, c] = es;
        //
        const {pageX,pageY,clientX,clientY,localX,localY,graphX,graphY} = eventPos(e)
        //
        v.style.left = `${graphX + 2}px`
        h.style.top = `${graphY + 2}px`
        c.style.left = `${graphX + 10}px`
        c.style.top = `${graphY + 10}px`
        //
        c.innerHTML = `
            <div>Offset(offsetX, offsetY): ${e.offsetX} x ${e.offsetY}</div>
            <div>Page(pageX, pageY): ${pageX} x ${pageY}</div>
            <div>Client(clientX, clientY): ${clientX} x ${clientY}</div>
            <div>Local Point: ${localX} x ${localY}</div>
            <div>Graph Point: ${graphX} x ${graphY}</div>
        `
    }

    const eventPos = (e: MouseEvent) => {
        const graph = main.graph;
        const pageX = e.pageX
        const pageY = e.pageY
        const clientX = e.clientX
        const clientY = e.clientY
        const p1 = graph.pageToLocal(pageX, pageY)
        const p2 = graph.localToGraph(p1);
        // const ox = p2.x || e.offsetX;
        // const oy = p2.y || e.offsetY;
        return { pageX, pageY, clientX, clientY, localX: p1.x, localY: p1.y,graphX:p2.x,graphY:p2.y,ex:e.offsetX,ey:e.offsetY }
    }

    return {
        enabled,
        toggle,
        eventPos
    }
}